<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Services\WxTokenService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class TokenController extends Controller
{
    /**
     * 获取 Token
     * @param Request $request
     * @return JsonResponse
     */
    public function getToken(Request $request): JsonResponse
    {
        $rule        = [
            "code"           => "required|string",
        ];
        $input       = $request->input();
        $validateRet = Validator::make($input, $rule);
        if ($validateRet->fails()) {
            return result(1, $validateRet->errors()->first());
        }

        $code = $input['code'];
        $userToken = new WxTokenService($code);
        try {
            $token = $userToken->getToken();
        } catch (\Exception $e) {
            return result(1, $e->getMessage());
        }
        return result(0, 'ok', ['token' => $token]);
    }

    public function getUser(Request $request)
    {
        $uid = WxTokenService::getCurrentUid();
        return $uid;
    }
}
